<script setup lang="ts">
import {Search} from '@element-plus/icons-vue'
import {comboFields} from "@/utils/field";
import {
  ComboForm,
  createProduct,
  getProductDetail,
  getProductOptions,
  getSearchProducts,
  ProductForm,
  ProductPageVO,
  updateProduct,
} from "@/api/product";
import {yesOrNoOpts_1} from "@/utils/status";

defineOptions({
  name: "ComboEdit",
  inheritAttrs: false,
});

const steps = ref<String[]>([
  "基本信息",
  "规格明细",
]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  productId: {
    type: Number,
    default: null,
  },
});

const emit = defineEmits(["updateVisble", "close", 'update:visible']);

const objFormRef = ref(ElForm);
const loading = ref(false);
const innerVisible = ref(false)

const word = ref(""); //关键词
const stepActive = ref(0);
const modelFields = comboFields();
const statusList = yesOrNoOpts_1();

const spec_groups = ref<ComboForm[]>([]);
const goodsList = ref<ProductPageVO[]>();

const originData = (): ProductForm => ({
  id: undefined,
  title: undefined,
  // sn: undefined,
  thumb: "",
  category_id: undefined,
  shop_id: undefined,
  stall_id: undefined,
  bag_price: undefined,
  price: undefined,
  cost_price: undefined,
  step: 0,
  status: 1,
  spec_type: 10,
  sort: 60,
  stock: undefined,
  weight: undefined,
  select_amount: 0,
  product_type: 1,
  content: undefined,
  product_feed: undefined,
  product_taste: undefined,
  min_buy: 1,
  limit_num: undefined,
  skus: undefined
})


watch(
  () => props.productId,
  (newVal) => {
    if (newVal) {
      loading.value = true;
      getProductDetail(newVal)
        .then(({data}) => {
          Object.assign(formData, data);
          if (formData['skus']) {
            Object.assign(spec_groups.value, formData['skus']);
          }

          initForm();
        }).finally(() => {
        loading.value = false;
      })
    } else {
      initForm();
      resetForm();
    }
  }
);

const current_role = localStorage.getItem("role_name");
const shopList = ref<any[]>([]);
const formData = reactive(originData());
if (current_role != "sys") {
  modelFields[0].shop_id.hide = true;
}

const rules = reactive([
  {
    title: [{required: true, message: "请输入名称", trigger: "blur"}],
    shop_id: [{required: true, message: "请选择所属店铺", trigger: "blur"}],
    stall_id: [{required: true, message: "请选择档口", trigger: "blur"}],
    category_id: [{required: true, message: "请选择分类", trigger: "blur"}],
    status: [{required: true, message: "请选择状态", trigger: "blur"}],
  },
  {
    price: [
      {required: true, message: "必填", trigger: "blur"},
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value <= 0) {
            return callback(new Error('请输入大于0'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    // stock_cal_type: [{required: true, message: "库存计算方式必填", trigger: "blur"}],
    select_amount: [
      {required: true, message: "选品总数量必填", trigger: "blur"},
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value <= 0) {
            return callback(new Error('请输入大于0'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
  },
]);

function initForm() {
  modelFields[0].shop_id.options = shopList.value;
  if (current_role !== "sys") {
    modelFields[0].category_id.options = shopList.value[0].categories || [];
    modelFields[0].stall_id.options = shopList.value[0].stalls || [];

    if (!parseInt(String(formData.id || 0))) {
      formData.shop_id = shopList.value[0].id || "";
    }
  }

  if (formData.shop_id) {
    modelFields[0].shop_id.options.map((e1: any) => {
      if (e1.id == formData.shop_id) {
        modelFields[0].stall_id.options = e1.stalls || [];
        modelFields[0].category_id.options = e1.categories || [];
      }
    });
  }

  if (parseInt(String(formData.id || 0))) {
    modelFields[0].shop_id.disabled = true;
    modelFields[0].category_id.disabled = true;
    modelFields[0].stall_id.disabled = true;
  } else {
    modelFields[0].shop_id.disabled = false;
    modelFields[0].category_id.disabled = false;
    modelFields[0].stall_id.disabled = false;
  }
}

function handleSubmit() {

  objFormRef.value.validate((valid: any) => {
    if (valid) {
      if (loading.value) {
        return;
      }

      const id = formData.id;
      formData.step = stepActive.value;
      if (stepActive.value == 1) {
        formData.skus = spec_groups.value;
      }
      loading.value = true;
      if (id) {
        updateProduct(id, formData).then(() => {
          if (stepActive.value == 1) {
            stepActive.value = 0;
            closeDialog(1)
          } else {
            stepActive.value = 1;
          }

        })
          .finally(() => (loading.value = false));
      } else {
        createProduct(formData)
          .then((data) => {
            if (stepActive.value == 1) {
              stepActive.value = 0;
              closeDialog(1)
            } else {
              Object.assign(formData, data.data)
              stepActive.value = 1;
            }
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function closeDialog(type?: any) {
  resetForm();
  stepActive.value = 0
  emit("close", type || 0);
}

function uploadSucess(res: any) {
  formData[res.name] = res.value || ''
}

function tabChanage(res: any) {
  stepActive.value = res || 0
}

/*添加规格组*/
function addSpecGroup() {
  spec_groups.value.push({
    title: "",
    amount: undefined,
    is_multi: 0,
    spec_items: [],
  })
}

//删除规格组
function deleteSpecGroup(idx?: any) {

  if (spec_groups.value[idx] != undefined) {
    if (spec_groups.value[idx].spec_items.length > 0) {
      ElMessage.error("请先删除规格值")
      return;
    }
    spec_groups.value.splice(idx, 1);
  }
}

/**
 * 删除规格值
 * @param specIdx
 * @param specVal
 */
function deleteSpecVal(specIdx: number, specValIdx: number) {
  if (spec_groups.value[specIdx] != undefined && spec_groups.value[specIdx]!.spec_items[specValIdx] != undefined) {
    spec_groups.value[specIdx]!.spec_items.splice(specValIdx, 1);
  }
}

/**
 * 下拉款选择
 */
function handleSelect(fkey: any, value: any) {

  if (fkey == 'shop_id') {
    modelFields[0].shop_id.options.map((e1: any) => {
      if (e1.id == value) {
        modelFields[0].category_id.options = e1.categories || [];
        modelFields[0].stall_id.options = e1.stalls || [];
        formData['stall_id'] = undefined;
        formData['category_id'] = undefined;
      }
    })
  }

}

function resetForm() {
  objFormRef.value?.resetFields();
  objFormRef.value?.clearValidate();
  Object.assign(formData, originData());

  goodsList.value = [];
  spec_groups.value = [];

  initForm();
}


/**
 * 初始化数据
 */
function initData() {
  stepActive.value = 0;

  getProductOptions().then(({data}) => {
    loading.value = false;
    modelFields[0].shop_id.options = data.shops || [];
    shopList.value = data.shops || [];
    initForm();

  }).finally(() => {
    loading.value = false;
  });
}


onMounted(() => {
  initData();
})

const ids = ref<number[]>([]);
const selectIdx = ref<number | undefined>();

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 显示选择商品框
 */
function showSelectGoods(idx?: number) {
  innerVisible.value = true;
  selectIdx.value = idx;

  if (formData.shop_id) { //店铺已选打开获取商品
    searchGood();
  }
}

function searchGood() {
  if (!formData.shop_id) {
    ElMessage.error("请先选择店铺");
    return
  }

  goodsList.value = [];
  loading.value = true;
  getSearchProducts({
    keyword: word.value || "",
    shop_id: formData.shop_id || 0
  }).then((res) => {
    goodsList.value = res.data || [];
  }).finally(() => {
    loading.value = false;
  })
}

//关闭内弹窗
function closeInnerDialog() {
  ids.value = [];
  goodsList.value = [];
  innerVisible.value = false;
  word.value = "";
}

//确认已选
function confirmSelectGoods() {
  if (goodsList.value!.length > 0) {
    goodsList.value!.map((item: any) => {
      if (ids.value.indexOf(item.id) != -1) {
        spec_groups.value[selectIdx.value!].spec_items.push({
          product_id: item.id,
          title: item.title,
          amount: 1,
          sn: item.sn,
        })
      }
    })
  }

  goodsList.value = [];
  selectIdx.value = undefined;
  innerVisible.value = false;
}

</script>

<template>

  <el-dialog
    v-model="props.visible"
    :title="productId?'编辑套餐':'新增套餐'"
    width="760px"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    @close="closeDialog"
    custom-class="form-edit"
  >
    <el-tabs type="border-card" v-model="stepActive" @tab-change="tabChanage">
      <el-tab-pane :name="index" :label="item + ''" v-for="(item,index) in steps"/>
    </el-tabs>
    <el-form ref="objFormRef" :model="formData" :rules="rules[stepActive]" label-width="160px">
      <template v-for="(field, fk) in modelFields[stepActive]">
        <el-form-item :label="field.title" :prop="fk.toString()" :key="fk"
                      v-if="!field.relateKey || (field.relateKey  && formData[field.relateKey] == field.relateVal)"
                      :class="field.hide ? 'el-hide':''">

          <div v-if="fk.toString() == 'skus' ">
            <div class="spec-group" v-for="(spec, spindex) in spec_groups">
              <div class="spec-group-title">
                <el-input v-model="spec.title" class="spec-input margin10-r" placeholder="请输入套餐项名称"/>
                <el-input v-model="spec.amount" class="spec-input" placeholder="请输入餐品数量"/>
                <el-button type="primary" link @click="showSelectGoods(spindex)">选择商品</el-button>
                <el-button @click="deleteSpecGroup(spindex)" type="info" text>删除</el-button>
              </div>

              <div class="spec-group-title">
                <el-text class="margin10-r">商品可多选</el-text>
                <el-radio-group v-model="spec.is_multi" class="span2">
                  <el-radio :label="Number(ok)" v-for="(op, ok) in statusList" :key="ok">{{ op }}</el-radio>
                </el-radio-group>
              </div>

              <div class="spec-group-list">
                <el-table :data="spec.spec_items" border style="width: 480px;" show-header class="spec-header">
                  <el-table-column label="序号" prop="sort" align="center" width="80">
                    <template #default="scope">
                      <el-input v-model="scope.row.sn" class="spec-input" placeholder="序号"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品名称" prop="title"/>
                  <el-table-column label="操作" align="center" width="80">
                    <template #default="scope">
                      <el-button @click="deleteSpecVal(spindex, scope.$index)" type="info" text>删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

            </div>

            <el-dialog
              :v-loading="loading"
              v-model="innerVisible"
              width="720"
              title="添加商品"
              append-to-body
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              class="dialog-inner"
            >
              <div class="mt-4" style="margin-bottom: 30px;">
                <el-input
                  v-model="word"
                  style="max-width: 460px"
                  placeholder="请输入商品名称"
                  class="input-with-select"
                  clearable
                  @change="searchGood"
                >
                  <template #append>
                    <el-button @click="searchGood()" :icon="Search"/>
                  </template>
                </el-input>
              </div>

              <el-table
                ref="multipleTableRef"
                :data="goodsList"
                border
                max-height="420"
                style="width: 100%;"
                show-header
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55"/>
                <el-table-column label="序号" prop="sort" align="center" width="60">
                  <template #default="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column label="商品编号" prop="id" align="center" width="100"/>
                <el-table-column label="商品名称" prop="title"/>
                <el-table-column prop="category_title" align="center" label="所属分类" width="180"/>
              </el-table>

              <template #footer>
                <div class="dialog-footer text-center">
                  <el-button type="primary" @click="confirmSelectGoods">新增</el-button>
                  <el-button @click="closeInnerDialog()">取消</el-button>
                </div>
              </template>
            </el-dialog>

            <el-button type="primary" size="default" @click="addSpecGroup">添加套餐项</el-button>
          </div>

          <el-radio-group v-model="formData[fk]" v-else-if="field.type == 'radio'" :class="field.class  || 'span2'">
            <el-radio
              :label="Number(ok)"
              v-for="(op, ok) in field.options"
              :key="ok"
            >{{ op }}
            </el-radio>
          </el-radio-group>
          <el-time-picker v-model="formData[fk]" :value-format="field.format" is-range range-separator="至"
                          start-placeholder="起始时间" end-placeholder="结束时间" v-else-if="field.type == 'timerange'" class="timerange"/>
          <el-select :disabled="field.disabled ? true : false" v-model="formData[fk]"
                     v-else-if="field.type == 'select'" :class="field.class || 'span2'"
                     @change="handleSelect(fk.toString(), formData[fk])">
            <el-option
              :label="op.title || ''"
              v-for="op in field.options"
              :value="Number(op.id)"
              v-if="field.range_key"
            />
            <el-option
              :label="op || ''"
              v-for="(op, ok) in field.options"
              :value="Number(ok)"
              v-else
            />
          </el-select>
          <single-upload
            :modelValue="formData[fk]"
            :fkey="String(fk)"
            @upload-sucess="uploadSucess"
            v-else-if="field.type == 'image'"
          />
          <el-input
            :disabled="field.disabled ? true : false"
            :type="field.type || 'text'"
            v-model="formData[fk]"
            :placeholder="'请输入' + field.title"
            :class="field.class || 'span2'"
            v-else
          />
        </el-form-item>
      </template>
      <div class="clear"></div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">{{ stepActive == 1 ? '保存' : '下一步' }}</el-button>
        <el-button @click="closeDialog" type="default">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.el-range-editor.el-input__wrapper{flex: 0.4}
.spec-group {
  margin-bottom: 10px;
  background: #ecf5ff;
  padding: 10px;
}

.spec-group .el-button {
  padding: 10px 5px;
  font-size: 12px;
  margin-left: 5px !important;
}

.spec-group-title {
  margin-bottom: 10px;
}

.spec-group-title .spec-input {
  width: 37% !important;
}

.spec-group-item .spec-item-input {
  width: 37%;
  margin-right: 2% !important;
}

.spec-group-item .spec-item-input:last-child {
  margin-right: 0 !important;
}

.spec-header .el-table__header thead tr > th {
  background: #f8f8f8;
}

.span2 {
  width: 40%;
}

.el-dialog__body {
  /*padding: 10px 20px !important;*/
  border: 1px solid #eee;
  margin: 0px 20px 30px !important;
}

.el-tabs--border-card {
  border: 0px !important;
}


.dialog-inner .el-dialog__body {
  border: 0px !important;
  padding-bottom: 30px !important;
}


th > .cell > .el-checkbox {
  display: none;
}

</style>
